import { Component } from '@angular/core';
import {FormBuilder, FormGroup, ReactiveFormsModule, Validators} from '@angular/forms';
import {NgIf} from "@angular/common";
import { HttpClient, HttpClientModule } from '@angular/common/http';
import { ImageCropperModule, ImageCroppedEvent, ImageTransform } from 'ngx-image-cropper';

@Component({
  selector: 'app-credit-card-form',
  templateUrl: './credit-card-form.component.html',
  standalone: true,
  imports: [
    ReactiveFormsModule,
    NgIf,
    HttpClientModule,
    ImageCropperModule
  ],
  styleUrls: ['./credit-card-form.component.css']
})
export class CreditCardFormComponent {
  cardForm: FormGroup;
  submitted = false;
  scanResult: string | null = null;
  scanning = false;

  imageChangedEvent: any = '';
  croppedImage: Blob | null = null;
  showCropper = false;
  originalFile: File | null = null;
  rotation = 0;
  scale = 1;
  transform: ImageTransform = {};

  constructor(private fb: FormBuilder, private http: HttpClient) {
    this.cardForm = this.fb.group({
      name: ['', [Validators.required]],
      number: ['', [Validators.required, Validators.pattern(/^\d{16}$/)]],
      expiry: ['', [Validators.required, Validators.pattern(/^(0[1-9]|1[0-2])\/\d{2}$/)]],
      cvv: ['', [Validators.required, Validators.pattern(/^\d{3,4}$/)]]
    });
  }

  get f() { return this.cardForm.controls; }

  onSubmit() {
    this.submitted = true;
    if (this.cardForm.invalid) {
      return;
    }
    alert('提交成功: ' + JSON.stringify(this.cardForm.value));
  }

  onFileSelected(event: Event) {
    const input = event.target as HTMLInputElement;
    if (input.files && input.files.length > 0) {
      this.originalFile = input.files[0];
      this.imageChangedEvent = event;
      this.showCropper = true;
    }
  }

  imageCropped(event: ImageCroppedEvent) {
    if (event.blob) {
      this.croppedImage = event.blob;
    }
  }

  rotate(angle: number) {
    this.rotation += angle;
    this.transform = {
      ...this.transform,
      rotate: this.rotation
    };
  }

  zoom(factor: number) {
    this.scale += factor;
    this.transform = {
      ...this.transform,
      scale: this.scale
    };
  }

  cancelCrop() {
    this.showCropper = false;
    this.imageChangedEvent = null;
    this.croppedImage = null;
    this.originalFile = null;
    this.rotation = 0;
    this.scale = 1;
    this.transform = {};
  }

  scanCard() {
    if (!this.croppedImage || !this.originalFile) {
      alert('请先选择并裁剪图片');
      return;
    }
    alert('正在识别，请稍候...');
    this.scanning = true;
    this.showCropper = false;
    const formData = new FormData();
    const croppedFile = new File([this.croppedImage], this.originalFile.name, { type: this.croppedImage.type });
    formData.append('file', croppedFile);

    this.http.post('http://172.18.32.40:18080/api/ocr/creditCard', formData, { responseType: 'text' })
      .subscribe({
        next: (res: string) => {
          console.log('OCR 结果:', res);
          try {
            const data = JSON.parse(res);
            this.cardForm.patchValue({
              name: data.cardHolder || '',
              number: data.cardNumber || '',
              expiry: data.expiryDate || ''
              // cvv 字段后端未返回，保持原样
            });
            this.scanResult = '识别成功，已自动填充表单';
          } catch {
            this.scanResult = res;
          }
        },
        error: () => {
          this.scanResult = '识别失败，请重试';
        },
        complete: () => {
          this.scanning = false;
        }
      });
  }
}
